package com.hd.util.html2pdf;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.File;
import com.lowagie.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
/**
 * @Author: hzhh123
 * @Date: 2018/10/27 15:06
 */
public class Html2pdf {
    /*
  * HTML转换为PDF
  *
  */
    public  void  HtmlToPdf(String inputFile,String outputFile) throws Exception{
        String url = new File(inputFile).toURI().toURL().toString();
        System.out.println(url);
        OutputStream os = new FileOutputStream(outputFile);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);
        // 解决中文支持问题
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont("c:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        // 解决图片的相对路径问题
//        String base=System.getProperty("user.dir");
//        renderer.getSharedContext().setBaseURL("file:///"+base+"/src/main/resources/Test/dog.bmp");
        renderer.layout();
        renderer.createPDF(os);
        os.close();
    }
    public static void main(String[] args) throws Exception {
        Html2pdf demo = new Html2pdf();
        String base=System.getProperty("user.dir");
        String inputFile = "D:\\workspace\\eclipse_workspace\\work1\\ssm_maven\\src\\main\\webapp\\test.html";
        String outputFile ="D:\\test.pdf";
        demo.HtmlToPdf(inputFile, outputFile);
    }
}
